from typing import Optional, Any, Dict
from pydantic import BaseModel, model_validator, ConfigDict, Field


class CommonText_response(BaseModel):
    # 开启允许从sql模型查询对象获取数据
    model_config = ConfigDict(from_attributes=True)
    id: Optional[int] = None
    kind: Optional[str] = None
    title: Optional[str] = None
    sketch: Optional[str] = None
    date: Optional[str] = None
    author: Optional[int] = None
    reads: Optional[int] = None
    pushes: Optional[int] = None
    thumbs: Optional[int] = None
    collects: Optional[int] = None
    index_image: Optional[str] = None
    visibility: Optional[str] = None
    comments: Optional[list] = None
    resource: Optional[str] =None
    tips:Optional[str] = None
    username:Optional[str] = None

    @model_validator(mode='before')
    def filter_fields(cls, data):
        # 定义允许的字段集合
        allowed_fields = {
            'id', 'kind', 'title', 'sketch', 'date', 'author',
            'reads', 'pushes', 'thumbs', 'collects',
            'index_image', 'visibility', 'comments', 'resource', 'tips','username'
        }

        if isinstance(data, dict):
            # 如果输入是字典，直接过滤
            return {k: v for k, v in data.items() if k in allowed_fields}
        else:
            # 如果输入是SQLAlchemy模型实例
            return {k: getattr(data, k) for k in allowed_fields if hasattr(data, k)}




class writer_community_text(CommonText_response):
    model_config = ConfigDict(from_attributes=True)
    id: Optional[int] = None


class CommonText_response_byuser(BaseModel):
    model_config = ConfigDict(from_attributes=True,populate_by_name=True)
    # 保持内部字段名为英文，但设置中文别名
    id: Optional[int] = Field(None, alias="uuid")
    kind: Optional[str] = Field(None, alias="类型")
    title: Optional[str] = Field(None, alias="标题")
    date: Optional[str] = Field(None, alias="日期")
    author: Optional[int] = Field(None, alias="作者ID")
    reads: Optional[int] = Field(0, alias="阅读量")
    thumbs: Optional[int] = Field(0, alias="点赞数")
    collects: Optional[int] = Field(0, alias="收藏数")

    @model_validator(mode='before')
    def filter_fields(cls, data):
        allowed_fields = {"id", "kind", "title", "date", "author" ,"reads", "thumbs", "collects"}
        if isinstance(data, dict):
            return {k: v for k, v in data.items() if k in allowed_fields}
        else:
            return {k: getattr(data, k) for k in allowed_fields if hasattr(data, k)}


class CommonText_response_gettext(BaseModel):
    # 用于渲染单个文本时
    model_config = ConfigDict(from_attributes=True, populate_by_name=True,)
    # 保持内部字段名为英文，但设置中文别名
    id: Optional[int] = Field(None, alias="uuid")
    kind: Optional[str] = Field(None, alias="类型")
    title: Optional[str] = Field(None, alias="标题")
    date: Optional[str] = Field(None, alias="日期")
    author: Optional[int] = Field(None, alias="作者ID")
    reads: Optional[int] = Field(0, alias="阅读量")
    thumbs: Optional[int] = Field(0, alias="点赞数")
    collects: Optional[int] = Field(0, alias="收藏数")
    username:Optional[str]=Field("匿名",alias="昵称")
    text:str
    user_to_text:Optional[dict]

    @model_validator(mode='before')
    # 注意由于是前置,那么这里的都要有
    def filter_fields(cls, data):
        allowed_fields = {"id", "kind","text","title", "date", "author", "reads", "thumbs", "collects","user_to_text","username"}
        if isinstance(data, dict):
            return {k: v for k, v in data.items() if k in allowed_fields}
        else:
            return {k: getattr(data, k) for k in allowed_fields if hasattr(data, k)}


class CommonText_response_first_comment(BaseModel):
    # 用于渲染单个文本时
    model_config = ConfigDict(from_attributes=True)
    # 保持内部字段名为英文，但设置中文别名
    uuid:Optional[str]
    id : Optional[int]
    author :  Optional[int]
    date : Optional[str]
    images :  Optional[str] = None
    reply_count :  Optional[int]
    like_count :  Optional[int]
    content:Optional[str]
    author_image:Optional[str]=None
    f_username:Optional[str]="匿名"
    user_to_comment:Optional[dict]=None

    @model_validator(mode='before')
    @classmethod
    def remove_sqlalchemy_internal_fields(cls, data: Any) -> Dict[str, Any]:
        if isinstance(data, dict):
            # 过滤掉 _sa_ 开头的键（SQLAlchemy 内部属性）
            return {k: v for k, v in data.items() if not k.startswith('_sa_')}
        else:
            # 如果是对象，先转换成 dict 再过滤
            data_dict = {k: getattr(data, k) for k in dir(data) if not k.startswith('_')}
            return {k: v for k, v in data_dict.items() if not k.startswith('_sa_')}


class CommonText_response_second_comment(BaseModel):
    # 用于渲染单个文本时
    # model_config = ConfigDict()
    # 保持内部字段名为英文，但设置中文别名
    uuid:Optional[str]
    id: Optional[int]
    author: Optional[int]
    date: Optional[str]
    f_author: Optional[int]
    images: Optional[str]=None
    content:Optional[str]
    like_count: Optional[int]
    author_image:Optional[str]
    s_username: Optional[str] = "匿名"
    user_to_comment: Optional[dict] = None
    double_two:Optional[str]='0'
    f_uuid:str
    @model_validator(mode='before')
    # 注意由于是前置,那么这些被允许的都要又
    def filter_fields(cls, data):
        allowed_fields = {"id", "author", "date", "f_author", "images", "like_count","content","author_image","s_username","uuid","user_to_comment","double_two","f_uuid"}
        if isinstance(data, dict):
            return {k: v for k, v in data.items() if k in allowed_fields}
        else:
            return {k: getattr(data, k) for k in allowed_fields if hasattr(data, k)}

class CommText_search_preinfo(BaseModel):
    model_config = ConfigDict(from_attributes=True, populate_by_name=True ,)
    # 保持内部字段名为英文，但设置中文别名
    id: Optional[int] = Field(None, alias="uuid")
    kind: Optional[str] = Field(None, alias="类型")
    # 这里为了处理关键字转义为字典
    title: Optional[list] = Field(None, alias="标题")
    date: Optional[str] = Field(None, alias="日期")
    reads: Optional[int] = Field(0, alias="阅读量")
    thumbs: Optional[int] = Field(0, alias="点赞数")
    collects: Optional[int] = Field(0, alias="收藏数")

    @model_validator(mode='before')
    # 注意由于是前置,那么这些被允许的都要有
    def filter_fields(cls, data):
        allowed_fields = {"id", "kind","title", "date", "reads", "thumbs", "collects"}
        if isinstance(data, dict):
            return {k: v for k, v in data.items() if k in allowed_fields}
        else:
            return {k: getattr(data, k) for k in allowed_fields if hasattr(data, k)}
